package com.hx.mypetstore.ui.Details;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hx.mypetstore.Bean.AddressBean;
import com.hx.mypetstore.Bean.GoodsBean;
import com.hx.mypetstore.R;
import com.hx.mypetstore.common.BaseCallback;
import com.hx.mypetstore.constant.OrderState;
import com.hx.mypetstore.constant.SPConstants;
import com.hx.mypetstore.network.HttpURL;
import com.hx.mypetstore.util.GenerateSequenceUtil;
import com.hx.mypetstore.util.LoginUtil;
import com.hx.mypetstore.util.SPUtil;
import com.hx.mypetstore.util.view.ImageDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.orhanobut.dialogplus.DialogPlus;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DetailsActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "详情页";
    /**
     * 返回图标
     */
    private ImageView imgBack;
    /**
     * 商品单价
     */
    private TextView detailPrice;
    /**
     * 商品名
     */
    private TextView detailName;
    /**
     * 商品剩余
     */
    private TextView detailNumber;
    /**
     * context
     */
    private Context mContext;
    /**
     * 商品描述
     */
    private TextView detailInfo;
    /**
     * 商品信息实体
     */
    private GoodsBean good;
    /**
     * 商品id
     */
    private String productId = "";

    /**
     * 商品图片
     * @param savedInstanceState
     */
    private ImageView imageView;

    /**
     * 用于从网络初始化UI的handler
     */
    /**
     * 购物车dialog
     */
    private DialogPlus mCartDialog;

    /**
     * 购买dialog
     */
    private DialogPlus mBuyDialog;

    /**
     * 购物车按钮
     */
    private Button mBtnCart;
    /**
     * 购买按钮
     */
    private Button mBtnBuy;
    /**
     * 购物车按钮点击回调事件
     */
    private BaseCallback cartCallback = new BaseCallback() {
        @Override
        public void sendMessage(final Object obj) {
            //判断登录状态
            if (LoginUtil.isLogin(mContext)) {

                //从SharedPreferences中获取用户id
                String userid = SPUtil.get(mContext,SPConstants.KEY_LOCAL_USER,"").toString();
                String url = HttpURL.ADDCART;
                //发送请求
                OkHttpClient okHttpClient = new OkHttpClient();
                RequestBody requestBody = new FormBody.Builder()
                        .add("userid",userid)
                        .add("goodid",good.getId().toString())
                        .add("num",obj.toString())
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, "onFailure: " + e.getMessage());
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        try {
                            JSONObject jsonObject = new JSONObject(response.body().string());
                            Message msg = Message.obtain();
                            Log.e(TAG, "结果"+jsonObject.toString() );
                            msg.obj = jsonObject.getString("message");
                            msg.what = 5;
                            //发送handler消息
                            uiHandler.sendMessage(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } else {
                //如果未登录
                uiHandler.sendEmptyMessage(-2);
            }

        }
    };
    /**
     * 购买按钮点击回调事件
     */
    private BaseCallback buyCallback = new BaseCallback() {
        @Override
        public void sendMessage(Object obj) {
            //判断登录状态
            if (LoginUtil.isLogin(mContext)) {
                //从SharedPreferences中获取用户id
                String userid = SPUtil.get(mContext,SPConstants.KEY_LOCAL_USER,"").toString();
                List<AddressBean> dataList = SPUtil.getDataList(mContext, SPConstants.TAG_ADDRESS_LIST, AddressBean.class);
                AddressBean add = new AddressBean();
                String orderid = GenerateSequenceUtil.generateSequenceNo();
                for(AddressBean addressBean : dataList)
                {
                    if(addressBean.getDefaults().equals("1"))
                        add = addressBean;
                }
                String url = HttpURL.ISORDER;
                //发送请求
                //计算价格
                Integer price = Integer.parseInt(obj.toString()) * good.getPrice();
                OkHttpClient okHttpClient = new OkHttpClient();
                RequestBody requestBody = new FormBody.Builder()
                        .add("id",orderid)
                        .add("name",add.getName())
                        .add("address",add.getAddress())
                        .add("phone",add.getPhone())
                        .add("state", OrderState.NOAPPLY.toString())
                        .add("goodname",good.getName())
                        .add("price",price.toString())
                        .add("userid",userid)
                        .add("number",obj.toString())
                        .add("goodid",good.getId().toString())
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, "onFailure: " + e.getMessage());
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        try {
                            JSONObject jsonObject = new JSONObject(response.body().string());
                            Message msg = Message.obtain();
                            Log.e(TAG, "结果"+jsonObject.toString() );
                            if(jsonObject.getBoolean("success"))
                                msg.what = 5;
                            else
                                msg.what = -5;
//                            发送handler消息
                            msg.obj = jsonObject.getString("message");
                            uiHandler.sendMessage(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } else {
                //如果未登录
                uiHandler.sendEmptyMessage(-2);
            }
        }
    };
    /**
     * 用于从网络初始化UI的handler
     */
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -5:
                    Toast.makeText(mContext, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case -2:
                    //未登录，需要登录！
                    Toast.makeText(mContext, "您还未登录！请先登录！", Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！获取商品类别失败！"
                            , Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "请求处理失败！获取商品类别失败！"
                            : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    //网络请求商品信息数据成功
                    initData();
                    break;
                case 3:
                    //添加进购物车回调
                    Toast.makeText(mContext, "添加进购物车" + msg.obj.toString(), Toast.LENGTH_LONG).show();
                    //dismiss掉dialog
                    mCartDialog.dismiss();
                    break;
                case 4:
                    //购买回调
                    Toast.makeText(mContext, "购买商品" + msg.obj.toString(), Toast.LENGTH_LONG).show();
                    //dismiss掉dialog
                    mBuyDialog.dismiss();
                    break;
                case 5:
                    //添加成功回调
                    Toast.makeText(mContext,"恭喜你"+msg.obj.toString(),Toast.LENGTH_LONG).show();
                    finish();
                    break;
                    default:
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        //获得context
        mContext = this;
        init();
        //获得商品id
        Intent intent = getIntent();
        productId = intent.getStringExtra("id");
        Log.e(TAG, "商品id "+productId );
        initData();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        good = SPUtil.getDataList(mContext, SPConstants.GOODS_LIST,GoodsBean.class).get(Integer.parseInt(productId));
        Log.e(TAG, "good"+good );
        detailName.setText(good.getName());
        detailNumber.setText("剩余："+good.getNumber().toString()+"件");
        detailInfo.setText(good.getDescribe());
        detailPrice.setText("￥ " +good.getPrice().toString()+"元");
        Log.e(TAG, "initData: "+good );
        //实例化ImageLoader
        ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(mContext);
        ImageLoader.getInstance().init(configuration);
        ImageLoader.getInstance().displayImage("assets://img/" + good.getImageid(), imageView);
    }

    /**
     * 绑定组件
     */
    private void init() {
        detailInfo = findViewById(R.id.detail_info);
        detailNumber = findViewById(R.id.detail_surplus);
        detailName = findViewById(R.id.detail_name);
        detailPrice = findViewById(R.id.detail_price);
        imgBack = findViewById(R.id.detail_back);
        imageView = findViewById(R.id.detail_img);
        mBtnCart = findViewById(R.id.btn_cart);
        findViewById(R.id.detail_back).setOnClickListener(this);
        mBtnCart.setOnClickListener(this);
        mBtnBuy = findViewById(R.id.btn_buy);
        mBtnBuy.setOnClickListener(this);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "点击图片放大" );
                imageView.setDrawingCacheEnabled(true);
                ImageDialog myImageDialog = new ImageDialog(v.getContext(),R.style.dialogWindowAnim,0,-300,imageView.getDrawingCache());
                myImageDialog.show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.detail_back:
                finish();
            case R.id.btn_cart:
                if (LoginUtil.isLogin(DetailsActivity.this)) {
                    MyCartDialog dialog = new MyCartDialog(DetailsActivity.this);
                    mCartDialog = dialog.createDialog(cartCallback);
                    mCartDialog.show();
                } else {
                    //Toast提示登录
                    uiHandler.sendEmptyMessage(-2);
                }
                break;
            case R.id.btn_buy:
                if (LoginUtil.isLogin(DetailsActivity.this)) {
                    MyCartDialog dialog = new MyCartDialog(DetailsActivity.this);
                    mBuyDialog = dialog.createDialog(buyCallback);
                    mBuyDialog.show();
                } else {
                    //Toast提示登录
                    uiHandler.sendEmptyMessage(-2);
                }
                break;
        }
    }

}